package com.hframe.typefilter;

import java.lang.reflect.Field;

/**
 * 根据枚举名转换为枚举类型
 * Created by heqian on 17-9-19.
 */
public class NameToEnum<T extends Enum> implements FilterRef<T, Object> {
    private Class<T> enumClass;

    public NameToEnum(Class<T> enumClass) {
        this.enumClass = enumClass;
    }

    @Override
    public T filter(Object object) throws Exception {
        if (null != enumClass && null != object && object instanceof String) {
            Field[] fields = enumClass.getDeclaredFields();
            for (Field field : fields) {
                if (!field.isEnumConstant())
                    continue;

                if (field.getName().toLowerCase().equals(((String) object).toLowerCase())) {
                    return (T) field.get(null);
                }
            }
        }
        return null;
    }
}
